package online.flytool.base.db;

import online.flytool.base.log.FlyLog;
import online.flytool.base.log.FlyLogFactory;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.logging.Logger;

/**
 * @author ：lingchong
 * date ：Created in 2022/7/3 16:16
 * @description：简单的数据库连接池
 * @modified By：
 * @version: $
 */
public class SimpleDateSource implements DataSource {
    private static FlyLog log = FlyLogFactory.getLog(SimpleDateSource.class.toString());

    private final ConnProperty connProperty;

    //连接池
    /*private LinkedList<Connection> pool = (LinkedList<Connection>) Collections.synchronizedList(new LinkedList<Connection>());*/
    /**
     * TODO 目前是线程不安全的，后面修改为线程安全的
     */
    private LinkedList<Connection> pool = new LinkedList<Connection>();

    /**
     * 通过配置属性生成数据源
     * @param property 配置属性
     */
    public SimpleDateSource(ConnProperty property) {
         this.connProperty=property;
        try {
            Class.forName(property.getDirerClassName());
        } catch (ClassNotFoundException e) {
            log.error("找不到驱动类！", e);
        }
    }

    /**
     * 获取一个数据库连接
     *
     * @return 一个数据库连接
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        synchronized (pool) {
            if (pool.size() > 0) return pool.removeFirst();
            else return makeConnection();
        }
    }

    /**
     * 连接归池
     *
     * @param conn
     */
    public void freeConnection(Connection conn) {
        pool.addLast(conn);
    }

    private Connection makeConnection() throws SQLException {
        return DriverManager.getConnection(connProperty.getUrl(), connProperty.getUser(), connProperty.getPwd());
    }

    public Connection getConnection(String username, String password) throws SQLException {
        return DriverManager.getConnection(connProperty.getUrl(), username, password);
    }

    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    public void setLoginTimeout(int seconds) throws SQLException {

    }

    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        /*return System.getLogger("simpleDateSource");*/
        return null;
    }

    @Override
    public ShardingKeyBuilder createShardingKeyBuilder() throws SQLException {
        return DataSource.super.createShardingKeyBuilder();
    }

    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}
